﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AntJoin.SignalR.Models;

namespace AntJoin.SignalR.Services
{
    /// <summary>
    /// 帮助类
    /// </summary>
    public class SignalRHubHelper
    {
        private readonly IEnumerable<IHubService> _hubServices;

        public SignalRHubHelper(IEnumerable<IHubService> hubServices)
        {
            _hubServices = hubServices;
        }

        public IHubService GetHubService(string typeName)
        {
            return _hubServices.First(a => a.GetType().Name.StartsWith(typeName));
        }

        public T GetHubService<T>() where T : class, IHubService
        {
            return _hubServices.First(a => a is T) as T;
        }


        /// <summary>
        /// 发送消息给单人
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="message"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public async Task SendMessage(long userId, BaseHubMessage message, string typeName)
        {
            await GetHubService(typeName).SendMessage(userId, message);
        }



        /// <summary>
        /// 发送消息给多人
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="message"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public async Task SendMessage(List<long> userIds, BaseHubMessage message, string typeName)
        {
            await GetHubService(typeName).SendMessages(userIds, message);
        }


        /// <summary>
        /// 发送消息给群组
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="message"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public async Task SendGroupMessage(string groupName, BaseHubMessage message, string typeName)
        {
            await GetHubService(typeName).SendGroupMessage(groupName, message);
        }


        /// <summary>
        /// 广播信息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public async Task SendAllMessage(BaseHubMessage message, string typeName)
        {
            await GetHubService(typeName).SendAllMessage(message);
        }
    }
}
